import axios from 'axios';
import store from '../store';
import router from "../router";
import Loading from "../utils/loading";

let baseUrl = `http://10.80.7.156:20000/`;

let api = axios.create({
    baseURL: baseUrl,
});

let parse = function (data) {
    return new Promise(function (resolve, reject) {
        if (data) {
            if (data.code === -1) {
                if (data.status === 401) {
                    store.dispatch('logout').then(() => {
                        router.push('/login');
                        Loading.hideLoad();
                    }).catch(e => {
                        console.log(e);
                    });
                    reject(data);
                } else {
                    resolve(data);
                    Loading.hideLoad();
                }
            } else {
                resolve(data);
            }
        } else {
            resolve({code: 0, msg: `API request error!`});
        }
    });
};

export default {
    get: async function (path) {
        if (store.state.token) {
            if (path.indexOf('?') !== -1) {
                path = path + '&token=' + store.state.token;
            } else {
                path = path + '?token=' + store.state.token;
            }
        }
        try {
            let res = await api.get(path);
            return parse(res.data);
        } catch (e) {
            console.error(e);
            return parse(null);
        }
    },

    post: async function (path, data = {}) {
        if (store.state.token) {
            data.token = store.state.token;
        }

        try {
            let res = await api.post(
                path,
                data,
                {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                },
            );
            return parse(res.data);
        } catch (e) {
            console.error(e);
            return parse(null);
        }
    },
};
